<script setup lang="ts">
  import { PropType, ref, computed } from "vue";
  import { ElForm, ElFormItem, FormInstance } from "element-plus";
  import SelectBase from "@/components/SelectBase.vue";
  import { copyObj } from "@/util";
  const
    props = defineProps({
      modelValue: { type: Object as PropType<gt.sql.orderStock>, default: format.def.order, },
      curd: { type: Number as PropType<gt.curd>, default: 2 }
    }),
    disabled = computed(() => {
      return !!props.modelValue.id;
    }),
    sb = ref<InstanceType<typeof SelectBase>>(),
    rules = ref({
      name: { required: true, message: "请填写标题", trigger: "blur", min: 1 },
      type: { required: true, message: "请选择商品类型", trigger: "blur", min: 1 },
      oid: { required: true, message: "请选择配送商户", trigger: "blur", min: 1 },
    }),
    gs = ref<Tree<gt.sql.group>>([]),
    entity = ref<FormInstance>();
  async function init() {
    if (!gs.value.length) {
      const t = (await gd.groupTree).find(e => e.id === "1");
      t?.children?.unshift(gd.group.findById("0") as any);
      if (t) {
        gs.value = t.children as any;
      }
    }
    const
      m = props.modelValue;
    m.createName = api.me.name;
    m.outGid = "";
    m.outGidName = "-";
  }
  init();
  function addIn() {
    if (sb.value) {
      sb.value.open("goods", "商品").then(r => {
        if (r) {
          if (!props.modelValue.in.find(e => e.goods == r.id)) {
            props.modelValue.in.push({
              sum: 0,
              des: "",
              goods: r.id,
              goodsName: r.name,
              goodsMoney: r.money,
            } as any);
          }
        }
      }).catch(() => { });
    }
  }

  function delRow(p: gt.sql.stockLog) {
    props.modelValue.in.splice(props.modelValue.in.indexOf(p), 1);
  }

  defineExpose({
    validate() {
      return new Promise<boolean>(async (resolve) => {
        const
          pm = props.modelValue,
          r = {
            name: pm.name,
            type: pm.type,
            des: pm.des,
            inGid: pm.inGid,
            outGid: pm.outGid,
            content: [] as { goods: string; sum: number; des: string; }[]
          };

        if (!props.curd) {
          try {
            pm.in.forEach((e, i) => {
              if (!(e.sum > 0)) {
                ElMessageBox.confirm(`出库详情第[${i + 1}]行未选择数量`, "错误", { type: "error", });
                throw null;
              }
              r.content.push({ goods: e.goods, sum: e.sum, des: e.des });
            });
          } catch (_) {
            return resolve(false);
          }
        }

        if (entity.value) {
          entity.value.validate().then(e => {
            if (e) {
              copyObj(props.modelValue, r);
            }
            resolve(e);
          }).catch(() => { resolve(false); });
        } else {
          resolve(false);
        }
      });
    },
    resetFields() { entity.value?.resetFields(); }
  });
</script>
<template>
  <ElForm class="order xw zb" ref="entity" :model="modelValue" :rules="rules" labelWidth="7em">
    <ElFormItem label="id" prop="id">
      <el-input v-model="modelValue.id" disabled placeholder="系统自动生成" />
    </ElFormItem>
    <ElFormItem label="创建时间" prop="createTime">
      <el-input :modelValue="modelValue.createTime ? modelValue._createTime : '系统自动生成'" disabled />
    </ElFormItem>
    <ElFormItem label="操作人" prop="createName">
      <el-input :modelValue="modelValue.createName" placeholder="系统自动生成" disabled />
    </ElFormItem>
    <ElFormItem label="交付时间" prop="sendTime">
      <el-input :modelValue="modelValue.sendTime ? modelValue._sendTime : '未交付'" disabled />
    </ElFormItem>
    <ElFormItem label="出库商户" prop="outGidName">
      <el-input :modelValue="modelValue.outGidName" placeholder="未找到" disabled />
    </ElFormItem>
    <ElFormItem label="收货时间" prop="recvTime">
      <el-input :modelValue="modelValue.recvTime ? modelValue._recvTime : '未收货'" disabled />
    </ElFormItem>
    <ElFormItem label="入库商户" prop="inGid">
      <el-select v-model="modelValue.inGid" placeholder="请选择入库商户" :disabled="!!curd">
        <el-option v-for="(a, ai) in gs" :key="ai" :value="a.id" :label="a.name" />
      </el-select>

    </ElFormItem>
    <ElFormItem label="标题" prop="name">
      <el-input v-model="modelValue.name" placeholder="请输入名称" :disabled="curd == 2" />
    </ElFormItem>
    <ElFormItem label="备注" prop="des" class="wf">
      <el-input v-model="modelValue.des" placeholder="请输入备注" :disabled="curd == 2" />
    </ElFormItem>
    <ElFormItem class="wf" label="入库详情" prop="out">
      <template #label>
        <div class="whf y je">
          <div class="el-form-item__label">入库详情</div>
          <el-button type="primary" class="mt1em" @click="addIn"
            :disabled="disabled || !modelValue.inGid">新增</el-button>
        </div>
      </template>
      <el-table stripe highlight-current-row :data="modelValue.in" class="wf ox" height="15em" type="expand"
        row-key="id">
        <el-table-column prop="goodsName" label="商品名称" show-overflow-tooltip />
        <el-table-column prop="goodsMoney" label="单价" show-overflow-tooltip />
        <el-table-column prop="sum" label="数量" width="160" show-overflow-tooltip>
          <template #default="{ row }">
            <el-input-number class="wf" v-model="row.sum" :min="0" :disabled="disabled" />
          </template>
        </el-table-column>
        <el-table-column prop="des" label="备注" width="160" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="wf x oh jc">
              <el-input class="wf" v-model="row.des" :disabled="!!curd" />
              <div v-if="curd < 2" class="ml04em sbss cr mac-ico-delete" @click="delRow(row)" />
            </div>
          </template>
        </el-table-column>
      </el-table>
    </ElFormItem>
    <SelectBase ref="sb" hideLabel />
  </ElForm>
</template>
<style lang="scss" scoped>
  .order {
    position: relative;
    >.el-form-item:not(.wf) {
      width: 49%;
    }
  }
</style>